import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => ({
    userDbId: localStorage.getItem("userDbId") || "",
    username: localStorage.getItem("username") || "",
    token: localStorage.getItem("token") || "",
    login_token: localStorage.getItem("login_token") || "",
    // 统一登录响应的用户信息
    userInfo: JSON.parse(localStorage.getItem("userInfo")) || null,
    // sign 统一登录用
    sign: localStorage.getItem("sign") || "",
    // 是否登录
    isLogin: localStorage.getItem("isLogin") === "true",
    // 用户权限
    permissions: JSON.parse(localStorage.getItem("permissions")) || ['user'], // 默认普通用户权限
  }),
  actions: {
    setUserDbId(userDbId) {
      this.userDbId = userDbId;
      localStorage.setItem("userDbId", userDbId); // ✅ 保证刷新后能还原
    },
    setUsername(username) {
      this.username = username;
      localStorage.setItem("username", username); // ✅ 保证刷新后能还原
    },
    setEmpNO(emp_no) {
      this.emp_no = emp_no;
      localStorage.setItem("emp_no", emp_no); // ✅ 保证刷新后能还原
    },    
    setToken(token) {
      this.token = token;
      localStorage.setItem("token", token);
    },
    clearToken() {
      this.token = "";
      localStorage.removeItem("token");
    },
    setLoginToken(token) {
      this.login_token = token;
      localStorage.setItem("login_token", token);
    },
    clearLoginToken() {
      this.login_token = "";
      localStorage.removeItem("login_token");
    },
    setSign(sign) {
      this.sign = sign;
      localStorage.setItem("sign", sign);
    },
    clearSign() {
      this.sign = "";
      localStorage.removeItem("sign");
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      localStorage.setItem("userInfo", JSON.stringify(userInfo)); // ✅ 保证刷新后能还原
    },
    clearUserInfo() {
      this.userInfo = null;
      localStorage.removeItem("userInfo");
    },

    setIsLogin(isLogin) {
      this.isLogin = isLogin;
      localStorage.setItem("isLogin", String(isLogin));
    },
    clearIsLogin(){
      this.isLogin = false;
      localStorage.removeItem("isLogin");
    },
    logout() {
      // 除此之外需要调用统一登录的登出接口
      fetch("https://gf-net.cn/auth/logout?access_token=" + this.token, {
        method: "GET"
      });

      this.userDbId = "";
      this.login_token = "";
      this.emp_no = "";
      this.username = "";
      this.token = "";
      this.isLogin = false;
      this.sign = "";
      this.userInfo = null;
      localStorage.removeItem("userDbId");
      localStorage.removeItem("emp_no");
      localStorage.removeItem("login_token");
      localStorage.removeItem("username");
      localStorage.removeItem("isLogin")
      localStorage.removeItem("token");
      localStorage.removeItem("sign");
      localStorage.removeItem("userInfo");
      localStorage.removeItem("permissions");
    },
    
    // 权限相关方法
    setPermissions(permissions) {
      this.permissions = permissions;
      localStorage.setItem("permissions", JSON.stringify(permissions));
    },
    
    // 检查是否有特定权限
    hasPermissions(requiredPermissions) {
      if (!Array.isArray(requiredPermissions)) {
        return false;
      }
      
      return requiredPermissions.some(permission => 
        this.permissions.includes(permission) || 
        this.permissions.includes('admin') // admin有所有权限
      );
    },
    
    // 检查是否有任何工具权限
    hasAnyToolPermission() {
      // 这个方法会在HeaderBar中被工具注册系统调用
      return this.permissions.length > 0;
    },
    
    // 加载用户权限（从后端获取）
    async loadUserPermissions() {
      try {
        // 这里可以调用后端API获取用户权限
        // 暂时使用模拟数据
        const mockPermissions = this.userDbId === '1' ? ['admin'] : ['user'];
        this.setPermissions(mockPermissions);
      } catch (error) {
        console.warn('加载用户权限失败:', error);
        // 如果加载失败，保持默认权限
      }
    },
  },
  // ✅ 关键：开启持久化
  persist: true,
});
